package com.etb.wisdom.eframe.system.action;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;

import com.etb.core.pojo.DataObject;
import com.etb.core.utils.DataUtil;
import com.etb.core.utils.ReflectionUtil;
import com.etb.web.action.ETBAction;
import com.etb.web.utils.WebUtil;
import com.etb.wisdom.eframe.model.OrgEmployee;

@Action("validate")
public class ValidateAction extends ETBAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4608771499174859382L;

	public void unique() {
		String result = PASS;
		String value = request.getParameter("value");
		String className = request.getParameter("className");
		String uniqueField = request.getParameter("uniqueField");
		String params = request.getParameter("params");
		
		try {
			DataObject dataObject = (DataObject) Class.forName(className).newInstance();
			ReflectionUtil.setValue(dataObject, uniqueField, value);
			if(StringUtils.isNotBlank(params)) {
				List<String> paramList = DataUtil.split(params, "&");
				for(String param: paramList) {
					List<String> keyValue = DataUtil.split(param, "=");
					if("id".equals(keyValue.get(0))) {
						id = keyValue.get(1);
					} else {
						ReflectionUtil.setValue(dataObject, keyValue.get(0), keyValue.get(1));
					}
				}
			}
			if(service.count(dataObject) > 0) {
				if(StringUtils.isNotBlank(id)) {
					DataObject original = (DataObject) Class.forName(className).newInstance();
					original.setId(id);
					service.extend(original);
					if(!ReflectionUtil.getValue(original, uniqueField).equals(value)) {
						result = UNPASS;
					}
				} else {
					result = UNPASS;
				}
			}
			WebUtil.render(result);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("唯一校验所配置的className无法找到", e);
		} catch (Exception e) {
			throw new RuntimeException("唯一校验所配置的className在实例化时出现异常", e);
		}
		OrgEmployee org = new OrgEmployee();
		org.setEmpcode(value);
	}
	
}
